package advanced.io;

import java.io.*;
import java.util.Date;

/**
 * 对象流  序列化
 * <p>
 * <p>
 * 实现了Serializeable接口的类 才可以序列化
 *
 *
 * <p>
 * ObjectInputStream
 * <p>
 * ObjectOutputStream
 */
public class L_ObjectInputStream {
    public static void main(String[] args) {
        byte[] bytes = objectOutput();
        objectInput(bytes);
    }

    public static byte[] objectOutput() {
        //        将字节数组中写出, 可以改为文件流
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream dos = null;
        try {
            dos = new ObjectOutputStream(new BufferedOutputStream(baos));

        } catch (IOException e) {
            e.printStackTrace();
        }
        //写出
        try {
            dos.writeObject(new Date());
            dos.writeInt(32);
            dos.writeUTF("编码辛酸泪");
            dos.writeBoolean(false);
            dos.writeChar('a');
            dos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return baos.toByteArray();
    }

    public static void objectInput(byte[] datas) {
        //顺寻与写出一致(即使不用也要读取出来)
        try {
            ObjectInputStream dis = new ObjectInputStream(new BufferedInputStream(new ByteArrayInputStream(datas)));
            Date date = (Date) dis.readObject();
            int age = dis.readInt();
            String msg = dis.readUTF();
            boolean flag = dis.readBoolean();
            char ch = dis.readChar();
            System.out.println(date.toString());
            System.out.println(age);
            System.out.println(flag);
            System.out.println(ch);
            System.out.println(msg);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

}
